var CODE = require("./code/CODE");
var des = require("../../des");
var pako = require('pako');
var res_restful = function (code, data) {
    var json_ = {};
    json_.status = code.status;
    json_.msg = code.msg;
    if (global.isDebug) {
        json_.data = data;
    } else if (data && this.reqToken && this.reqAuthToken && this.reqPrivateToken) {
        var strEnc = des.strEnc(JSON.stringify(data), this.reqToken, this.reqPrivateToken, this.reqAuthToken);
        json_.data = pako.deflate(strEnc, {to: 'string'});
    } else if (data) {
        json_.data = pako.deflate(JSON.stringify(data), {to: 'string'});
    }
    this.json(json_);
    this.end();
};

var res_restful_suc = function (data) {
    res_restful.call(this, CODE.SUCCESS, data);
};

var res_restful_fai = function (data) {
    res_restful.call(this, CODE.FAILED, data);
};
var restful = function (req, res, next) {
    res.setHeader("Access-Control-Allow-Origin", "*");
    res.setHeader("content-type", "application/json");
    res.restful = res_restful;
    res.restfulsuc = res_restful_suc;
    res.restfulfai = res_restful_fai;
    next();
};
exports = module.exports = restful;